package org.everyday;

import java.util.*;

/**
 * @version v1.0.0
 * 创建时间：2022/7/19 09:01
 */
public class MyCalendarTwo {
    // 差分数组思想
    TreeMap<Integer, Integer> cnt;

    public MyCalendarTwo() {
        cnt = new TreeMap<Integer, Integer>();
    }

    public boolean book(int start, int end) {
        cnt.put(start, cnt.getOrDefault(start, 0) + 1);
        cnt.put(end, cnt.getOrDefault(end, 0) - 1);
        int pre = 0;

        for (Map.Entry<Integer, Integer> entry : cnt.entrySet()) {
            Integer freq = entry.getValue();
            pre += freq;

            if (pre > 2) {
                cnt.put(start, cnt.getOrDefault(start, 0) - 1);
                cnt.put(end, cnt.getOrDefault(end, 0) + 1);
                return false;
            }
        }
        return true;
    }
}
